package com.lin.nio.channel.threads;

import com.lin.nio.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 用于处理多个客户端的读写事件，来分摊单个线程压力
 */
@Slf4j
public class WorkerServer implements Runnable {
    // 工作线程
    private Thread workThread;

    private String workerName;

    // 用于管理通道
    private Selector selector;


    public WorkerServer() {
    }

    public WorkerServer(String workerName) {
        this.workerName = workerName;
    }

    public void register(SocketChannel sc) throws IOException {
        if (selector == null) selector = Selector.open();
        selector.wakeup();
        sc.configureBlocking(false);
        sc.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(16));

        log.info("registered...{}", sc);
        // 创建一个线程独立工作
        if (this.workThread == null) {
            workThread = new Thread(this);
            workThread.setName(workerName);
            workThread.start();
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                selector.select();

                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();

                    ByteBuffer dst = (ByteBuffer) key.attachment();
                    ((SocketChannel) key.channel()).read(dst);

                    log.info("收到客户端消息：{}", ByteBufferUtil.debugAll(dst));
                    iter.remove();
                }
            }
        } catch (IOException e) {
            log.error("worker出错：", e);
        }
    }
}
